import 'dart:io';

import 'package:simple_server/src/base_context.dart';
import 'package:simple_server/src/header.dart';
import 'package:simple_server/src/json.dart';
import 'package:simple_server/src/safe_http_response.dart';

class Context extends BaseContext {
  final HttpRequest request;
  final SafeHttpResponse response;
  final String method;
  final String path;
  final JsonMap query;
  final HeaderMap headers;

  Context(this.request)
      : response = SafeHttpResponse(request.response),
        method = request.method.toLowerCase(),
        path = request.uri.path,
        query = request.uri.queryParameters,
        headers = request.headers.toFullMap();

  @override
  dynamic operator [](String key) {
    final value = super[key];
    if (value != null) return value;
    final queryValue = query[key];
    if (queryValue != null) return queryValue;
    final headerMapValue = headers[key]?.firstOrNull;
    if (headerMapValue != null) return headerMapValue;
    final headerValue = request.headers.value(key);
    return headerValue;
  }

  @override
  void write(Object? object) {
    super.write(object);
    response.write(object);
  }

  @override
  void writeln([Object? object = ""]) {
    super.writeln(object);
    response.writeln(object);
  }

  @override
  set statusCode(int code) => response.statusCode = code;

  @override
  void json(dynamic data) {
    response.headers.contentType = ContentType.json;
    super.json(data);
  }

  @override
  JsonMap toJson() {
    return {
      if (query.isNotEmpty) 'query': query,
      ...super.toJson(),
    };
  }
}
